package br.com.viewcar.util;

import java.util.Date;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import br.com.viewcar.web.bean.BaseBean;
import com.sun.xml.internal.ws.util.ByteArrayDataSource;

public class MailUtil extends BaseBean{

	public static String sendEmail(String to, String subject, String msg) throws Exception  {

		Properties props = System.getProperties();
		props.put("mail.smtp.host", "smtp.fortalnet.com.br");
		props.put("mail.smtp.auth", "true");

		Authenticator authenticator = new Authenticator() {
			public PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication("checkrota", "fortal");
			}
		};

		Session session = Session.getInstance(props, authenticator);

		MimeMessage mimeMessage = new MimeMessage(session);
		mimeMessage.setFrom(new InternetAddress(CheckrotaUtil.MAIL));
		mimeMessage.setRecipients(Message.RecipientType.TO, new InternetAddress[] {new InternetAddress(to)});
		mimeMessage.setSubject(subject);
		mimeMessage.setText(msg);
		mimeMessage.setSentDate(new Date());

		Transport.send(mimeMessage);
		return SUCCESS;
	}
	
	public static String sendEmailWithFile(String to, String subject, String fileName, String msg, byte[] bytes, String mime) throws Exception  {

		Properties props = System.getProperties();
		props.put("mail.smtp.host", "smtp.fortalnet.com.br");
		props.put("mail.smtp.auth", "true");

		Authenticator authenticator = new Authenticator() {
			public PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication("checkrota", "fortal");
			}
		};

		Session session = Session.getInstance(props, authenticator);
		MimeMessage mimeMessage = new MimeMessage(session);
		mimeMessage.setFrom(new InternetAddress(CheckrotaUtil.MAIL));
		mimeMessage.setRecipients(Message.RecipientType.TO, new InternetAddress[] {new InternetAddress(to)});
		mimeMessage.setSubject(subject);
		MimeBodyPart texto = new MimeBodyPart();

		texto.setText(msg);

		MimeBodyPart anexo = new MimeBodyPart(); 

		ByteArrayDataSource fds = new ByteArrayDataSource(bytes, mime);

		anexo.setDataHandler(new DataHandler(fds));
		anexo.setFileName(fileName);

		Multipart mp = new MimeMultipart();  
		mp.addBodyPart(texto);  
		mp.addBodyPart(anexo);  
		mimeMessage.setContent(mp);
		mimeMessage.setSentDate(new Date());
		Transport.send(mimeMessage);

		return SUCCESS;
	}
}